package com.tanhua.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.tanhua.model.mongo.UserLocation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Circle;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.Metrics;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.geo.GeoJsonPoint;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@DubboService
public class UserLocationApiImpl implements UserLocationApi {

    @Autowired
    private MongoTemplate mongoTemplate;

    //保存或者更新
    public void save(Long userId, Double lat, Double lon, String addrStr) {
        //1、查询当前用户是否存在地理位置信息
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        boolean exists = mongoTemplate.exists(query, UserLocation.class); //true-存在
        //判断是否存在
        if(exists) {
            //2、如果存在，更新
            //update tal set location = ? where userId=?
            Update update = new Update();
            update.set("location",new GeoJsonPoint(lon, lat));
            update.set("address",addrStr);
            mongoTemplate.updateFirst(query,update,UserLocation.class);
        }else {
            //3、如果不存在，保存
            UserLocation ul = new UserLocation();
            ul.setUserId(userId);
            ul.setAddress(addrStr);
            ul.setCreated(System.currentTimeMillis());
            ul.setLocation(new GeoJsonPoint(lon, lat));
            mongoTemplate.save(ul);
        }
    }

    //搜索附近,返回附近人的id
    public List<Long> searchNear(Long userId, String miles) {
        //1、查询圆点，当前用户所在的坐标点
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query = Query.query(criteria);
        UserLocation location = mongoTemplate.findOne(query, UserLocation.class);
        GeoJsonPoint point = location.getLocation();
        //2、创建半径（距离）
        Double value = Double.valueOf(miles);
        Distance distance = new Distance(value/1000, Metrics.KILOMETERS); //数据，单位
        //3、绘制圆形
        Circle circle = new Circle(point,distance);
        //4、根据圆形，查询地理位置
        Criteria criteria1 = Criteria.where("location").withinSphere(circle);//查询坐标点，在圆点以内
        Query query1 = Query.query(criteria1);
        List<UserLocation> list = mongoTemplate.find(query1, UserLocation.class);
        //5、返回
        return CollUtil.getFieldValues(list,"userId",Long.class);
    }
}
